package pers.lance.firstweb.processtor;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import pers.lance.firstweb.bean.User;

import java.io.Writer;
import java.util.List;

public class DomProcesstorWithDom4j implements DomProcesstor {
    @Override
    public void user2Html(List<User> list, Writer writer) throws Exception {
        Document doc = new DOMDocument();
        Element html = new DOMElement("html");
        doc.setRootElement(html);
        Element body = new DOMElement("body");
        Element table = new DOMElement("table");
        for (User user : list) {
            Element tr = new DOMElement("tr");
            Element td0 = new DOMElement("td");
            Element td1 = new DOMElement("td");
            Element td2 = new DOMElement("td");
            Element td3 = new DOMElement("td");

            td0.setText(user.getName());
            td1.setText(user.getPassword());
            td2.setText(user.getBirth().toString());
            td3.setText(user.getMajor());

            tr.add(td0);
            tr.add(td1);
            tr.add(td2);
            tr.add(td3);
            table.add(tr);
        }
        body.add(table);
        html.add(body);

        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        XMLWriter xmlWriter = new XMLWriter(writer, format);
        writer.write("<!DOCTYPE html>");
        xmlWriter.write(html);
        xmlWriter.close();
    }
}
